package com.jiuyin.dianjing.ui.activity.match;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.SpinnerArrayAdapter;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.PMUtil;
import com.jiuyin.dianjing.util.RegexTool;
import com.jiuyin.dianjing.util.ScreenUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.DateTimeHourPicker;

import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DateTimePicker;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ADDRESS;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_BONUS_RULE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETE_BEGINTIME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETE_ENDTIME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETE_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_FLOCK;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAME_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAME_RULE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INTRO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ISSPONSOR;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_JOINNUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_CREATE_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_ENTER_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MOBILE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PUBLICITY;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_REGISTRATION_BEGANTIME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_REGISTRATION_ENDTIME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SCHEME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SCOPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SPONSOR;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SPONSOR_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TACTICS;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_WAY_INDEPENDENT_HOST;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_WAY_SPONSORED;

/**
 * 赛事自主举办创建页
 */
public class MatchCreateFillIndependentHostActivity extends BaseActivity implements View.OnTouchListener {
    @BindView(R.id.edt_sponsor)
    EditText edtSponsor;
    @BindView(R.id.edt_tv_phone)
    EditText edtPhone;
    @BindView(R.id.edt_event_notification_group)
    EditText edtEventNotificationGroup;
    @BindView(R.id.edt_principal)
    EditText edtPrincipal;
    @BindView(R.id.edt_introduction_initiator)
    EditText edtIntroductionInitiator;
    @BindView(R.id.edt_event_name)
    EditText edtEventName;
    @BindView(R.id.tv_competition_time_from)
    TextView tvCompetitionTimeFrom;
    @BindView(R.id.tv_competition_time_to)
    TextView tvCompetitionTimeTo;
    @BindView(R.id.tv_registration_time_from)
    TextView tvRegistrationTimeFrom;
    @BindView(R.id.tv_registration_time_to)
    TextView tvRegistrationTimeTo;
    @BindView(R.id.edt_competition_site)
    EditText edtCompetitionSite;
    @BindView(R.id.edt_unit_number)
    Spinner spinner;
    @BindView(R.id.edt_make_bonuses)
    EditText edtMakeBonuses;
    @BindView(R.id.edt_regulations_rules)
    EditText edtRegulationsRules;
    @BindView(R.id.tv_event_planning)
    TextView tvEventPlanning;
    @BindView(R.id.tv_effect_publicity)
    TextView tvEffectPublicity;
    @BindView(R.id.edt_event_planning)
    EditText edtEventPlanning;
    @BindView(R.id.edt_effect_publicity)
    EditText edtEffectPublicity;

    /**
     * 比赛开始时间
     */
    String competitionTimeFrom;
    /**
     * 比赛结束时间
     */
    String competitionTimeTo;

    /**
     * 报名开始时间
     */
    String registrationTimeFrom;
    /**
     * 报名结束时间
     */
    String registrationTimeTo;

    /**
     * 赛事类型
     */
    private String mMatchType;

    /**
     * 举办方式
     */
    private String mMatchWay;
    /**
     * 参赛方式
     */
    private String mMatchEnterType;

    private String mGameId;
    /**
     * 赛事主图
     */
    private String mTheme;

    private static final String[] unitNumbers = {"请选择", "4", "8", "16", "32", "64"};
    private ArrayAdapter<String> adapter;
    private String unitNumber;
    private static final String ZERO = "00";

    @Override
    protected int setLayoutId() {
        return R.layout.activity_match_create_fill_independent_host;
    }

    @Override
    protected void initData() {
        adapter = new SpinnerArrayAdapter(this, unitNumbers);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                unitNumber = "";
                if (position != 0) {
                    unitNumber = unitNumbers[position];
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void initView() {
        setStatus();
        setEditTextListener();
    }

    private void setStatus() {
        Intent intent = getIntent();
        String title = intent.getStringExtra(KEY_MATCH_CREATE_TYPE);
        mMatchType = intent.getStringExtra(KEY_MATCH_TYPE);
        mMatchWay = intent.getStringExtra(KEY_MATCH_CREATE_TYPE);
        mMatchEnterType = intent.getStringExtra(KEY_MATCH_ENTER_TYPE);
        mGameId = intent.getStringExtra(KEY_GAME_ID);
        mTheme = intent.getStringExtra(KEY_COMPETE_LOGO);
        if (title.equals(MATCH_WAY_INDEPENDENT_HOST)) {
            title = getString(R.string.match_create_independent_host);
            dealSponsoredStatus(false);
        } else if (title.equals(MATCH_WAY_SPONSORED)) {
            title = getString(R.string.match_create_sponsored);
            dealSponsoredStatus(true);
        }
        setTitle(title);
    }

    private void setEditTextListener() {
        edtIntroductionInitiator.setOnTouchListener(this::onTouch);
        edtMakeBonuses.setOnTouchListener(this::onTouch);
        edtRegulationsRules.setOnTouchListener(this::onTouch);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        setStatus();
    }

    @OnClick({R.id.bt_submit, R.id.tv_competition_time_from, R.id.tv_competition_time_to, R.id.tv_registration_time_from, R.id.tv_registration_time_to})
    public void onViewClicked(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.bt_submit:
                submit();
                break;
            case R.id.tv_competition_time_from:
            case R.id.tv_competition_time_to:
            case R.id.tv_registration_time_from:
            case R.id.tv_registration_time_to:
                onYearMonthDayTimePicker(id);
                break;
        }
    }

    /**
     * 提交
     */
    private void submit() {
        boolean isEmpty = false;
        String sponsor = edtSponsor.getText().toString();
        String phone = edtPhone.getText().toString();
        String eventNotificationGroup = edtEventNotificationGroup.getText().toString();
        String principal = edtPrincipal.getText().toString();
        String introductionInitiator = edtIntroductionInitiator.getText().toString();
        String eventName = edtEventName.getText().toString();
        String competitionSite = edtCompetitionSite.getText().toString();
        String makeBonuses = edtMakeBonuses.getText().toString();
        String regulationsRules = edtRegulationsRules.getText().toString();
        String eventPlanning = edtEventPlanning.getText().toString();
        String effectPublicity = edtEffectPublicity.getText().toString();
        Calendar selectedDate = Calendar.getInstance();
        int year = selectedDate.get(Calendar.YEAR);
        int month = selectedDate.get(Calendar.MONTH) + 1;
        int day = selectedDate.get(Calendar.DATE);
        int hour = selectedDate.get(Calendar.HOUR_OF_DAY);
        String time = year + "-" + appendZero(month) + "-" + appendZero(day) + " " + appendZero(hour) + ":" + ZERO;
        if (TextUtils.isEmpty(eventNotificationGroup)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(competitionTimeFrom)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(competitionTimeTo)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(registrationTimeFrom)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(registrationTimeTo)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(sponsor)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(principal)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(introductionInitiator)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(eventName)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(competitionSite)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(makeBonuses)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(unitNumber)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(regulationsRules)) {
            isEmpty = true;
        } else if (TextUtils.isEmpty(phone)) {
            isEmpty = true;
        }
        if (edtEventPlanning.getVisibility() != View.GONE) {
            if (TextUtils.isEmpty(eventPlanning)) {
                isEmpty = true;
            }
        }
        if (edtEffectPublicity.getVisibility() != View.GONE) {
            if (TextUtils.isEmpty(effectPublicity)) {
                isEmpty = true;
            }
        }
        if (isEmpty) {
            showDialog(getString(R.string.dialog_content_tips));
            return;
        }
        int number = Integer.parseInt(unitNumber);
        if (number == 0) {
            showDialog(getString(R.string.dialog_team_number));
            return;
        } else {
            if (!(number % 4 == 0)) {
                showDialog(getString(R.string.dialog_team_number_tip));
                return;
            }
        }
        if (competitionTimeFrom.compareTo(competitionTimeTo) >= 0) {
            showDialog(getString(R.string.dialog_time_tips));
            return;
        }
        if (registrationTimeFrom.compareTo(registrationTimeTo) >= 0) {
            showDialog(getString(R.string.dialog_time_tips));
            return;
        }
        if (competitionTimeFrom.compareTo(registrationTimeTo) <= 0) {
            showDialog(getString(R.string.dialog_time_tips));
            return;
        }
        if (competitionTimeFrom.compareTo(time) < 0) {
            showDialog(getString(R.string.dialog_time_tips));
            return;
        }
        if (registrationTimeFrom.compareTo(time) < 0) {
            showDialog(getString(R.string.dialog_time_tips));
            return;
        }

        if (!RegexTool.instance().isMobile(phone)) {
            showDialog(getString(R.string.login_normal_phone_tips));
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_SPONSOR, sponsor);
        params.put(KEY_MOBILE, phone);
        params.put(KEY_FLOCK, eventNotificationGroup);
        params.put(KEY_SPONSOR_NAME, principal);
        params.put(KEY_INTRO, introductionInitiator);
        params.put(KEY_NAME, eventName);

        params.put(KEY_REGISTRATION_BEGANTIME, registrationTimeFrom);
        params.put(KEY_REGISTRATION_ENDTIME, registrationTimeTo);
        params.put(KEY_COMPETE_BEGINTIME, competitionTimeFrom);
        params.put(KEY_COMPETE_ENDTIME, competitionTimeTo);

        params.put(KEY_ADDRESS, competitionSite);
        params.put(KEY_JOINNUM, unitNumber);
        params.put(KEY_SCOPE, mMatchType);
        params.put(KEY_ISSPONSOR, mMatchWay);
        params.put(KEY_GAME_ID, mGameId);
        params.put(KEY_TACTICS, mMatchEnterType);
        params.put(KEY_BONUS_RULE, makeBonuses);
        params.put(KEY_GAME_RULE, regulationsRules);
        params.put(KEY_COMPETE_LOGO, mTheme);

        if (edtEventPlanning.getVisibility() != View.GONE) {
            params.put(KEY_SCHEME, eventPlanning);
        }
        if (edtEffectPublicity.getVisibility() != View.GONE) {
            params.put(KEY_PUBLICITY, effectPublicity);
        }

        JSONObject jsonObject = new JSONObject(params);
        getApiHelper().appCreateCompetition(jsonObject.toString(), data -> {
            ToastUtil.showLong(data);
            PMUtil.getInstance().finishAc(MatchCreateActivity.class);
            finish();
        });
    }

    private String appendZero(int date) {
        if (date < 10) {
            return "0" + date;
        } else {
            return String.valueOf(date);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }

    @Override
    public void onBackPressed() {
        goTargetActivity(MatchCreateActivity.class);
    }

    private void showDialog(String str) {
        View view = LayoutInflater.from(this).inflate(R.layout.tip_dialog_layout, null, false);

        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();

        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtil.getScreenWidth(this) / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
        //设置背景透明
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView confirm = view.findViewById(R.id.tv_confirm);
        TextView content = view.findViewById(R.id.tv_content);
        content.setText(str);
        confirm.setOnClickListener(v -> dialog.dismiss());
    }

    /**
     * 年月日时间选择
     * id 控件
     */

    private void onYearMonthDayTimePicker(final int id) {
        Calendar selectedDate = Calendar.getInstance();
        DateTimeHourPicker picker = new DateTimeHourPicker(MatchCreateFillIndependentHostActivity.this, DateTimePicker.HOUR_24);
        picker.setActionButtonTop(false);
        picker.setDateRangeStart(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH) + 1, selectedDate.get(Calendar.DATE));
        picker.setDateRangeEnd(selectedDate.get(Calendar.YEAR) + 10, 12, 10);
        picker.setSelectedItem(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH) + 1, selectedDate.get(Calendar.DATE), selectedDate.get(Calendar.HOUR), selectedDate.get(Calendar.MINUTE));
        picker.setTimeRangeStart(0, 0);
        picker.setTimeRangeEnd(23, 59);
        picker.setCanLinkage(false);
        picker.setTitleText("请选择");
        picker.setWeightEnable(true);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLUE);//线颜色
        config.setAlpha(120);//线透明度
        config.setVisible(true);//线不显示 默认显示
        picker.setLineConfig(config);
        picker.setOuterLabelEnable(true);
        picker.setOnDateTimePickListener((DateTimeHourPicker.OnYearMonthDayTimePickListener) (year, month, day, hour, minute) -> {
            String time = year + "-" + month + "-" + day + " " + hour + ":" + ZERO;
            String time2 = month + "-" + day + " " + hour + ":" + ZERO;
            switch (id) {
                case R.id.tv_competition_time_from:
                    competitionTimeFrom = time;
                    tvCompetitionTimeFrom.setText(time2);
                    break;
                case R.id.tv_competition_time_to:
                    competitionTimeTo = time;
                    tvCompetitionTimeTo.setText(time2);
                    break;
                case R.id.tv_registration_time_from:
                    registrationTimeFrom = time;
                    tvRegistrationTimeFrom.setText(time2);
                    break;
                case R.id.tv_registration_time_to:
                    registrationTimeTo = time;
                    tvRegistrationTimeTo.setText(time2);
                    break;
            }
        });
        picker.show();
    }

    /**
     * 处理赞助举办的控件显示与否
     *
     * @param result true(显示)
     *               false(隐藏)
     */
    private void dealSponsoredStatus(boolean result) {
        if (result) {
            tvEventPlanning.setVisibility(View.VISIBLE);
            tvEffectPublicity.setVisibility(View.VISIBLE);
            edtEventPlanning.setVisibility(View.VISIBLE);
            edtEffectPublicity.setVisibility(View.VISIBLE);
        } else {
            tvEventPlanning.setVisibility(View.GONE);
            tvEffectPublicity.setVisibility(View.GONE);
            edtEventPlanning.setVisibility(View.GONE);
            edtEffectPublicity.setVisibility(View.GONE);
        }
    }
}
